<template>
  <div>
    <div>
      <el-select
        v-model="keywords"
        filterable
        remote
        reserve-keyword
        placeholder="请输入关键词"
        value-key="id"
        :remote-method="remoteMethod"
        :loading="loading"
        :clearable="true"
        size="mini"
        @change="currentSelect"
        style="width: 100%"
      >
        <el-option
          v-for="item in options"
          :key="item.id"
          :label="item.name"
          :value="item"
          class="one-text"
        >
          <span style="float: left">{{ item.name }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.district }}</span>
        </el-option>
      </el-select>
    </div>
    <div id="container" class="container"></div>
    <div class="info-box">
      <p>详细地址：{{ form.address }}</p>
    </div>
  </div>
</template>
<script
  src="https://webapi.amap.com/maps?v=1.4.15&key=80baaf54dbcc54d16e124872c4f2c04b&plugin=AMap.DistrictSearch"></script>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";

window._AMapSecurityConfig = {
  //安全密钥
  securityJsCode: "eb9b4b70fa2e590486c0e9a062d0cf4f",
};
export default {
  name: "Zhezhao",
  props: {
    createRegion: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      //地图实例
      map: null,
      // 选中的地址和经纬度
      form: {
        address: '',
        lng: "",
        lat: "",
      },
      loading: false,
      //检索提示
      AutoComplete: null,
      //搜索提示信息
      options: [],
      keywords: '',
    }
  },
  methods: {
    initMap() {
      console.log('&&&&&&&&&',this.createRegion)
      AMapLoader.load({
        key: "80baaf54dbcc54d16e124872c4f2c04b",
        version: "2.0",
        //插件在这里引入
        plugins: ['AMap.DistrictSearch', "AMap.Geocoder", "AMap.AutoComplete"]
      }).then((AMap) => {
        this.map = new AMap.Map("container", {
          resizeEnable: true,
          //地图初始的缩放倍数
          zoom: 13,
          //初始化后地图展示的中心位置
          center: [this.createRegion.centerLat, this.createRegion.centerLng],
        });
        //这是创建遮罩的方法
        this.initPolygon(this.createRegion.adCode, this.map);
        //地址逆解析插件
        this.geoCoder = new AMap.Geocoder({
          //城市设为北京，默认：“全国”
          city: "010",
          //范围，默认：500
          radius: 1000,
        });
        //搜索提示插件
        this.AutoComplete = new AMap.AutoComplete({city: "全国"});
        //点击获取经纬度;
        this.map.on("click", (e) => {
          //获取经纬度
          this.form.lng = e.lnglat.lng;
          this.form.lat = e.lnglat.lat;
          //清除点
          this.removeMarker();
          //标记点
          this.setMapMarker();
        });
      }).catch(e => {
        console.log(e);
      })
    },
    initPolygon(city, map) {
      AMap.plugin('AMap.DistrictSearch', function () {
        new AMap.DistrictSearch({
          extensions: 'all',
          subdistrict: 0
        }).search(city, function (status, result) {
          let outer = [
            new AMap.LngLat(-360, 90, true),
            new AMap.LngLat(-360, -90, true),
            new AMap.LngLat(360, -90, true),
            new AMap.LngLat(360, 90, true)
          ];
          let holes = result.districtList[0].boundaries;
          let pathArray = [outer];
          pathArray.push.apply(pathArray, holes);
          //添加遮罩样式
          let polygon = new AMap.Polygon({
            pathL: pathArray,
            strokeColor: '#00eeff',
            strokeWeight: 1,
            fillColor: '#71B3ff',
            fillOpacity: 0.5
          });
          polygon.setPath(pathArray);
          map.add(polygon);
        })
      })
    },
    /** 搜索 */
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.AutoComplete.search(query, (status, result) => {
            for (let i in result.tips) {
              if (result.tips[i].location) {
                if (result.tips[i].adcode === this.createRegion.adCode) {
                  this.options.push(result.tips[i])
                }
              }
            }
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
    /** 选中提示 */
    currentSelect(val) {
      //清空时不执行后面代码
      if (!val) {
        return;
      }
      this.form = {
        lng: val.location.lng,
        lat: val.location.lat,
        address: val.district + val.location.name
      };
      this.$emit('chooseData', this.form);
      //清除点
      this.removeMarker();
      //标记点
      this.setMapMarker();
    },
    /** 清除点 */
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
      }
    },
    /** 标记点 */
    setMapMarker() {
      // 自动适应显示想显示的范围区域
      // this.map.setFitView();
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.form.lng, this.form.lat],
      });
      //逆解析地址
      this.toGeoCoder();
      // this.map.setFitView();
      this.map.add(this.marker);
    },
    /** 逆解析地址 */
    toGeoCoder() {
      let lnglat = [this.form.lng, this.form.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === "complete" && result.regeocode) {
          this.form.address = result.regeocode.formattedAddress;
          this.$emit('chooseData', this.form);
        }
      });
    }
  },
  mounted() {
    this.initMap();
  },
  beforeDestroy() {
    this.map.destroy();
    this.map = null;
  }
}
</script>

<style scoped>
.container {
  width: 900px;
  height: 500px;
}
</style>
